package chapter12.section3;

/*程序12-5b：更新后的业务处理线程类*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Processor1205 extends Thread {
	Socket s;

	public Processor1205(Socket s) {
		super();
		this.s = s;
	}

	@Override
	public void run() {
		String address = s.getInetAddress().getHostAddress();
		BufferedReader in = null;
		PrintWriter out = null;
		try {
			// 封装输入流，以便以文本形式处理来自客户端的请求
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			// 封装输出流，以文本方式输出到输出流中，ture表示自动提交
			out = new PrintWriter(s.getOutputStream(), true);
			String info = null;// 保存每次从输入流中读到的请求信息
			boolean working = true;
			while (working) {
				info = in.readLine();
				// 解析客户端发来的业务请求
				String[] req = info.split(",");
				String type = req[0];// 业务类型
				if (type.equals("bye")) {// 客户端结束工作
					working = false;
					continue;
				}
				String id = req[1];// 交易账户的id
				int amount = Integer.parseInt(req[2]);// 交易金额
				// 寻找对应的Account对象
				Account account = AccountPool.getAccount(id);
				String resp = null;
				if (account == null) {
					resp = "fail：无此账户";
				} else {
					// 更新账户信息,组织返回信息
					if (type.equals("deposit")) {
						account.setBalance(account.getBalance() + amount);
						resp = "ok：" + account.getBalance();
					} else if (type.equals("query")) {
						resp = "ok：" + account.getBalance();
					}
				}
				// 将响应信息回送给客户端
				out.println(resp);
			}
			s.close();
		} catch (IOException e) {
			System.out.println("关闭来自" + address + "的客户端通信失败！");
		}
	}
}